#pragma once

#include "AbstractRequestService.h"
#include "RedisStore.h"
#include "RequestDispatcher.h"

namespace zeroplus::mq
{
    class AdminService : public AbstractRequestService
    {
    private:
        std::shared_ptr<RedisStore> redisStore_;
        RequestDispatcher dispatcher_;

    public:
        AdminService(std::shared_ptr<BrokerMediator> mediator)
            : AbstractRequestService(mediator),
              redisStore_(RedisStore::getInstance(BrokerConfig::getInstance().redisAddr))
        {
            dispatcher_.RegisterHandler<transport::RequestCode::UPDATE_AND_CREATE_TOPIC, transport::TopicCreateAndUpdateRequest, transport::TopicCreateAndUpdateResponse>(
                std::bind(&AdminService::ProcessTopicCreateAndUpdateRequest, this, std::placeholders::_1));
        }

        std::optional<transport::ReplyCommand> ProcessRequest(const transport::RequestCommand &cmd) override
        {
            return dispatcher_.Process(cmd);
        }

        transport::TopicCreateAndUpdateResponse ProcessTopicCreateAndUpdateRequest(const transport::TopicCreateAndUpdateRequest &request)
        {
            LOG_DEBUG("处理topic创建请求");
            std::string topic = request.topic();
            if (!redisStore_->IsTopicExists({topic}))
            {
                LOG_ERROR("register topic %s", topic.c_str());
                redisStore_->CreateMQ(topic);
            }
            // 响应客户端
            transport::TopicCreateAndUpdateResponse response;
            response.set_code(transport::ResponseCode::SUCCESS);
            return response;
        }
    };
} // namespace zeroplus::mq
